'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【createSystemNotification】云函数被调用，event：', event);

  const { userId, title, content, type = 'task_status', category = 'task' } = event;

  if (!userId) {
    return { 
      success: false, 
      message: '用户ID缺失' 
    };
  }

  try {
    // 创建系统通知记录
    const notificationData = {
      user_id: userId,
      type: type,
      category: category,
      title: title || '任务纠纷处理结果',
      content: content || '您发布的任务"系统通知"的纠纷已由管理员处理，处理结果：任务时间已延长7天',
      related_id: '68cbb4228b0da441dc035df0', // 示例任务ID
      related_type: 'task',
      priority: 'high',
      action_url: `/pages/system/DisputeDetail/DisputeDetail?id=68cbb4228b0da441dc035df0`,
      action_text: '查看详情',
      is_read: false,
      status: 'active',
      create_time: new Date(),
      update_time: new Date()
    };

    console.log('【createSystemNotification】创建通知数据：', notificationData);

    // 插入数据库
    const result = await db.collection('notification-messages').add(notificationData);

    console.log('【createSystemNotification】通知创建结果：', result);

    return {
      success: true,
      message: '系统通知创建成功',
      data: {
        notificationId: result.id,
        ...notificationData
      }
    };

  } catch (e) {
    console.error('【createSystemNotification】异常:', e);
    return { 
      success: false, 
      message: '系统通知创建失败：' + e.message 
    };
  }
};
